package com.polaris.live.dialog_fragment.room_background

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.viewModels
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.databinding.PartyPopupRoomBackgroundBinding
import com.polaris.live.dialog.RoomDiyBackgroundDetailDialog
import com.polaris.live.dialog_fragment.room_background.fragment.RoomBackgroundFragment
import com.polaris.live.net.userService
import com.polaris.live.resp.back_resp.UploadTimesConfig
import com.polaris.live.ui.message.fragment.dialog.BottomDialogFragment
import com.polaris.live.utils.fragment.attachFragment

/**
 *  房间背景
 * @author Created by 天晴 on 2024/7/17 19:18
 * @since 1.0.0
 **/
class RoomBackgroundPopup : BottomDialogFragment() {

    private val mAnchorId by lazy { arguments?.getLong("anchorId") }

    private val mViewModel by viewModels<BaseViewModel>()

    private lateinit var mBinding: PartyPopupRoomBackgroundBinding

    private var mUploadTimesConfig: UploadTimesConfig? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        mBinding = PartyPopupRoomBackgroundBinding.inflate(inflater, container, false)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val bottomView = mBinding.vLine
        val lp = bottomView.layoutParams as ViewGroup.LayoutParams
        lp.height = NavigationBarUtils.getNavigationBarHeight(requireContext())
        bottomView.layoutParams = lp

        initView()
    }

    private fun initView() {
        childFragmentManager.attachFragment(mBinding.flFragment.id) {
            RoomBackgroundFragment().apply {
                arguments = bundleOf("anchorId" to mAnchorId)
            }
        }
        initListener()
        initObserver()
    }

    private fun initObserver() {
        mViewModel.request({ userService.getPartyDiyBackground() }, {
            mUploadTimesConfig = it.uploadTimesConfig
        })
    }

    private fun initListener() {
        mBinding.closeImg.setOnSingleClickListener {
            dismiss()
        }
        mBinding.ivWhat.setOnSingleClickListener {
            mUploadTimesConfig?.let { it1 -> RoomDiyBackgroundDetailDialog.show(requireContext(), it1) }
        }
    }

    companion object {

        fun show(context: FragmentManager, anchorId: Long) {
            RoomBackgroundPopup().apply {
                arguments = bundleOf("anchorId" to anchorId)
            }.show(context, "RoomBackgroundPopup")
        }
    }
}